package com.onlinelibrary.service.impl;

import com.onlinelibrary.mapper.UserMapper;
import com.onlinelibrary.pojo.Book;
import com.onlinelibrary.pojo.User;
import com.onlinelibrary.result.Result;
import com.onlinelibrary.service.UserService;
import com.onlinelibrary.util.MailUtil;
import com.onlinelibrary.util.MinioUtil;
import com.onlinelibrary.util.SaltMD5Util;
import com.onlinelibrary.util.UserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@Service
public class UserServiceImpl01 implements UserService {

    @Value("${headUrl}")
    private String headUrl;

    //临时时存储验证码的Redis
    private final StringRedisTemplate redisTemplate;

    private final UserMapper userMapper;

    //对user内字段进行格式校验的工具类
    private final UserUtil userUtil;

    //发送邮箱的工具类
    private final MailUtil mailUtil;
    //minio
    private final MinioUtil minioUtil;


    @Override
    public Result list() {
        List<User> users = userMapper.list();
        System.out.println(users);
        return new Result(10000, "获取成功", users);
    }

    @Override
    public Result getUser(User user) {
        User userData = userMapper.getUser(user);
        if (userData != null) {
            return new Result(10000, "获取成功", userData);
        } else
            return new Result(1, "获取失败");
    }

    @Override
    public Result register(User user) {
        User user1 = userMapper.getUser(user);
        if (user1!=null){
            return new Result(1, "用户已存在");
        }
        //对用户输入的格式进行校验
        if (!userUtil.UserVerify(user)) {
            return new Result(1, "格式错误");
        }
        //从redis中获取邮箱验证码，并做验证
        String value = redisTemplate.opsForValue().get(user.getEmail() + "_code");
        if (value != null) {
            value = value.trim();
        } else {
            return new Result(1, "未发送验证码或验证码已过期");
        }
        if (Objects.equals(user.getNickName(), value)) {
            //将用户密码加密
            String md5password = SaltMD5Util.generateSaltPassword(user.getPassword());
            user.setPassword(md5password);
            //设置用户的默认头像
            user.setHeadUrl(headUrl);
            user.setNickName("用户昵称");
            Integer result = userMapper.register(user);
            if (result > 0) {
                return new Result(10000, "注册成功");
            } else {
                return new Result(1, "注册失败");
            }
        } else {
            return new Result(1, "验证码错误");
        }


    }

    @Override
    public Result login(User user) {
        //对用户输入的格式进行校验
        if (!userUtil.UserVerify(user)) {
            return new Result(1, "格式错误");
        }
        User userData = userMapper.login(user);
        if (userData != null) {
            //将现有密码与数据库中的加密密码进行校验
            boolean result = SaltMD5Util.verifySaltPassword(user.getPassword(), userData.getPassword());
            if (result) {
                return new Result(10000, "登录成功", userData);
            } else {
                return new Result(1, "密码错误");
            }
        } else {
            return new Result(1, "该用户不存在");
        }
    }

    @Override
    public Result sendEmailCode(User user) {
        //对用户输入的格式进行校验
        if (!userUtil.UserVerify(user)) {
            return new Result(1, "格式错误");
        }
        String email = user.getEmail();
        //获取一个随机验证码
        String code = userUtil.getCode();
        //向目标邮箱发送验证码
        boolean isSend = mailUtil.sendTextMailMessage(email, "网上图书借阅系统", "你的验证码为：" + code);
        if (isSend) {
            //发送成功后，将验证码存入redis，五分钟后过期
            redisTemplate.opsForValue().set(email + "_code", code, 300);
            return new Result(10000, "发送成功");
        } else {
            return new Result(1, "发送失败");
        }

    }

    @Override
    public Result loginByEmail(User user) {
        //对用户输入的格式进行校验
        if (!userUtil.UserVerify(user)) {
            return new Result(1, "格式错误");
        }
        //通过邮箱获取用户信息
        User userData = userMapper.getUserByEmail(user);
        if (userData != null) {
            //从redis中获取邮箱验证码，并做验证
            String value = redisTemplate.opsForValue().get(user.getEmail() + "_code");
            if (value != null) {
                value = value.trim();
            } else {
                return new Result(1, "未发送验证码或验证码已过期");
            }
            //把验证码临时存在nickName里面
            if (Objects.equals(user.getNickName(), value)) {
                return new Result(10000, "登录成功", userData);
            } else {
                return new Result(1, "验证码错误");
            }
        } else {
            return new Result(1, "该用户不存在");
        }
    }

    @Override
    public Result updateUser(User user) {
        if (user.getIdNumber()!=null){
            boolean idCard = userUtil.isIDCard(user.getIdNumber());
            if (!idCard){
                return new Result(1,"身份证格式错误");
            }
        }
        Integer result = userMapper.updateUser(user);
        if (result > 0) {
            User user1 = new User();
            user1.setId(user.getId());
            User userData = userMapper.getUser(user1);
            return new Result(10000, "修改成功", userData);
        } else {
            return new Result(1, "修改失败");
        }
    }

    @Override
    public Result updateHeadUrl(MultipartFile file, String id) {
//        String headUrl = minioUtil.addUserHeadImage(file, id);
        if (id.endsWith("-username")){
            String substring = id.substring(0, (id.length() - "-username".length()));
            User user = new User();
            user.setUsername(substring);
            User user1 = userMapper.getUser(user);
            id=user1.getId().toString();
        }
        String headUrl = minioUtil.addDataInBucket(file, id, "userhead");
        if (headUrl==null){
            return new Result(1,"头像上传失败");
        }
        //创建一个临时User对象，传入新url和id
        User user = new User();
        user.setHeadUrl(headUrl);
        System.out.println(id);
        user.setId(Integer.parseInt(id));
        //在数据库中更新头像url
        Integer result = userMapper.updateUser(user);
        if (result > 0) {
            //将更新后的数据返回前端
            User user1 = userMapper.getUser(user);
            return new Result(10000, "头像上传成功！", user1);
        } else {
            return new Result(1, "上传失败");
        }
    }

    @Override
    public Result getTableData(User user) {
        user.setId((user.getId()-1)*user.getIsAdmin());
        List<User> users=userMapper.getTableData(user);
        return new Result(10000,"获取成功",users);
    }

    @Override
    public Result deleteUser(User user) {
        if (user.getId()!=null){
            Integer i=userMapper.deleteUser(user);
            if (i>0){
                return new Result(10000,"删除成功");
            }else {
                return new Result(1,"删除失败");
            }
        }else {
            return new Result(1,"id为空");
        }
    }

    @Override
    public Result insertBookHouse(User user) {
        //获取数据，检测是否有bookHouse（没有直接添加）
        User userData = userMapper.getUser(user);
        String bookHouse = userData.getBookHouse();
        if (bookHouse!=null){
            String[] bookHouseSplit = bookHouse.split(",");
            if (Arrays.asList(bookHouseSplit).contains(user.getBookHouse())){
                return new Result(10000,"该书籍已存在");
            }
            user.setBookHouse(bookHouse+","+user.getBookHouse());
        }
        Integer i = userMapper.updateUser(user);
        if (i>0){
            return new Result(10000,"添加成功");
        }else {
            return new Result(1,"添加失败");
        }
    }

    @Override
    public Result getBookHouse(User user) {
        User userData = userMapper.getUser(user);
        String bookHouse = userData.getBookHouse();
        if (bookHouse==null){
            return new Result(10000,"获取成功",null);
        }
        String[] bookHouseSplit = bookHouse.split(",");
        List<Book> books = userMapper.selectBooksByIsbns(Arrays.stream(bookHouseSplit).toList());
        if (books!=null){
            return new Result(10000,"获取成功",books);
        }

        return null;
    }

    @Override
    public Result findByIsbns(String isbns) {
        String[] split = isbns.split(",");
        List<Book> books = userMapper.selectBooksByIsbns(Arrays.stream(split).toList());
        System.out.println("获取成功"+books);
        if (books!=null){
            return new Result(10000,"获取成功",books);
        }else
            return new Result(1,"获取失败");
    }

    @Override
    public Result deleteByIsbn(User user) {
        User userData = userMapper.getUser(user);
        System.out.println(user);
        System.out.println(userData);
        if (userData.getBookHouse()!=null){
            String[] split = userData.getBookHouse().split(",");
            List<String> list1 = new ArrayList<>(Arrays.stream(split).toList());
            String[] userSplit = user.getBookHouse().split(",");
            ArrayList<String> list2 = new ArrayList<>(Arrays.stream(userSplit).toList());
            list1 = list1.stream()
                    .filter(item -> !list2.contains(item))
                    .toList();
            user.setBookHouse(String.join(",", list1));
            System.out.println(user);
            Integer i = userMapper.updateUser(user);
            if (i>0){
                return new Result(10000,"删除成功");
            }else {
                return new Result(1,"删除失败");
            }
        }else {
            return new Result(1,"该书籍不存在");
        }

    }

    @Override
    public Result updatePassword(User user) {
        User userData = userMapper.getUser(user);
        if (user.getState()==1){
            if (userData!=null){
                //原密码正确的话
                if (SaltMD5Util.verifySaltPassword(user.getNickName(), userData.getPassword())){
                    //将用户密码加密
                    user.setPassword(SaltMD5Util.generateSaltPassword(user.getPassword()));
                    Integer i=userMapper.updatePassword(user);
                    if (i>0){
                        return new Result(10000,"修改成功");
                    }else {
                        return new Result(1,"修改失败");
                    }
                }else {
                    return new Result(1,"原密码错误");
                }
            }else {
                return new Result(1,"用户不存在");
            }
        }else {
            if (user.getEmail().equals(userData.getEmail())){
                //从redis中获取邮箱验证码，并做验证
                String value = redisTemplate.opsForValue().get(user.getEmail() + "_code");
                if (value != null) {
                    value = value.trim();
                } else {
                    return new Result(1, "未发送验证码或验证码已过期");
                }
                //把验证码临时存在nickName里面
                if (Objects.equals(user.getNickName(), value)) {
                    user.setPassword(SaltMD5Util.generateSaltPassword(user.getPassword()));
                    Integer i=userMapper.updatePassword(user);
                    if (i>0){
                        return new Result(10000,"修改成功");
                    }else {
                        return new Result(1,"修改失败");
                    }
                } else {
                    return new Result(1, "验证码错误");
                }
            }else {
                return new Result(1,"邮箱错误");
            }

        }

    }

    @Override
    public Result updateUserBack(User user) {
        System.out.println(user);
        User user1 = userMapper.getUser(user);
        user.setId(user1.getId());
        user.setUsername(null);
        System.out.println(user);
        Integer i = userMapper.updateUser(user);
        if (i>0){
            return new Result(10000,"修改成功");
        }else {
            return new Result(1,"修改失败");
        }
    }
}
